package io.github.edwinliu.anynet;

import android.util.Log;

import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import static io.github.edwinliu.anynet.AnyNet.NETWORK_TYPE_NONE;

public class SocketController {
    static String TAG = "AnyNet";

    public static boolean getVpn()
    {
        String  ret= sendToServer("get:"+ProviderUtils.KEY_NAME_VPN+";");
        ret=ret.substring(0,ret.length()-1);

        String[] rets=ret.split(":");
        if((rets.length==2)&&rets[0].endsWith("OK"))
        {
            return  Boolean.parseBoolean(rets[1]);
        }

        return false;
    }


    public static String setVpn(boolean isChecked)
    {
         return   sendToServer("set:"+ProviderUtils.KEY_NAME_VPN+"="+isChecked+";");
    }

    public static String setType(int type)
    {
         return  SocketController.sendToServer("set:"+ProviderUtils.KEY_NAME_NETTYPE+"="+type+";");
    }

    public static int getType()
    {
        String  ret= sendToServer("get:"+ProviderUtils.KEY_NAME_NETTYPE+";");
        ret=ret.substring(0,ret.length()-1);

        String[] rets=ret.split(":");
        if((rets.length==2)&&rets[0].endsWith("OK"))
        {
            try {
                return  Integer.parseInt(rets[1]);
            }catch (NumberFormatException e)
            {
                Log.d(TAG, "getType "+e.toString());
            }
        }

        return NETWORK_TYPE_NONE;
    }


    public static String sendToServer(String command) {
        byte[] output = null;
        byte[] buffer = new byte[1000];
        int nbBytesRead = -1;
        String strBuffer = "KO:INIT;";
        try {
            Socket clientSocket = new Socket("localhost", 43210);
            try {
                output = command.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                Log.d(TAG, "UnsupportedEncodingException");
            }
            clientSocket.getOutputStream().write(output);
            InputStream inputStream = clientSocket.getInputStream();
            try {
                clientSocket.setSoTimeout(1000);
                nbBytesRead = inputStream.read(buffer);
                if(nbBytesRead>0)
                    strBuffer = new String(buffer, "UTF-8");

                Log.d(TAG, "inputStream "+strBuffer);
                return strBuffer;
            } catch (InterruptedIOException e) {
                Log.d(TAG, "InterruptedIOException "+e.toString());
            }

            clientSocket.close();
        } catch (Exception e) {
            Log.d(TAG, "Exception "+e.getMessage());
            return strBuffer;
        }
        return strBuffer;
    }


}
